import { Component, OnInit } from '@angular/core'
import { Router, ActivatedRoute } from '@angular/router'
import * as moment from 'moment';

import { PageTitle } from './page-title'
import { Type } from './type'
import { TypeService } from './type.service'
import { User } from './user'
import { UserService } from './user.service'
import { Project } from './project'
import { ProjectService } from "./project.service"
import { Task } from './task'
import { TaskService } from "./task.service"
import { Stage } from './stage'
import { StageService } from './stage.service'
import { Milestone } from "./milestone";
import { MilestoneService } from './milestone.service'

@Component({
  selector: 'project-edit',
  templateUrl: "./project-edit.component.html",
  styleUrls: [ "./project-edit.component.css" ]
})
export class ProjectEditComponent implements OnInit {
  id: string
  mine: User
  types: Array<Type>
  users: Array<User>
  stages: Array<Stage> = [ ]
  task: Task = new Task()
  project: Project = new Project()
  submitting = false
  disabled = true
  projectShowed: boolean
  taskShowed: boolean
  tasks: Array<Task> = [ ]
  current_task: Array<Task>=[ ]
   top_date: string
  bottom_date: string

  constructor(private route: ActivatedRoute,
              private typeService: TypeService,
              private userService: UserService,
              private projectService: ProjectService,
              private milestoneService: MilestoneService,
              private taskService: TaskService,
              private stageService: StageService,
              private pageTitle: PageTitle,
              private router: Router) { }

  ngOnInit(): void {
    this.pageTitle.back = "/projects"
    this.pageTitle.title = "项目详情"
    var routeSnapshot = this.route.snapshot
    this.id = routeSnapshot.params['project_id']
     this.userService.getUserMine().then(user => {
      this.mine = user
      if (user.manager){
         this.projectService.get(this.id).then(project => {
         this.project = project
        })
         var argv = { project_id: this.id }
        this.taskService.get_task(argv).then(tasks => this.settask(tasks))
      }
    }) 
  }

  setUser() {
    this.userService.getUserMine().then(user => {
      this.mine = user
      if (this.project.leader_id == user.id || user.manager)
        this.disabled = false
    })
  }

  createTask(): void {
    this.taskShowed = true
    var routeSnapshot = this.route.snapshot
    this.id = routeSnapshot.params['project_id']
    this.setStageList()
    this.task = new Task()
    this.task.project_id = this.id
    this.projectService.get(this.id).then(project => {
      this.project = project
      this.task.project = project
      this.setUser()
    })
     this.userService.getList().then(users => {
      this.users = users
     /* if (users[0])
        this.task.receiver_id = users[0].id*/
    })
  }


   updateTask(task_id): void {
    this.taskShowed = true
    var routeSnapshot = this.route.snapshot
    this.id = routeSnapshot.params['project_id']
    this.setStageList()
    this.taskService.get(task_id).then(task => this.task = task)
    this.task.project_id = this.id
    this.projectService.get(this.id).then(project => {
      this.project = project
      this.task.project = project
      this.setUser()
    })
     this.userService.getList().then(users => {
      this.users = users
     /* if (users[0])
        this.task.receiver_id = users[0].id*/
    })
    var argv = { project_id: this.id }
    this.taskService.get_task(argv).then(tasks => this.settask(tasks))
  }

  setStageList(): void {
    if (!this.id) return ;
    this.stageService.getList(this.id).then(stages => {
      this.stages = stages
    })
 }

  delete(i,id): void {
    if(id){
      this.milestoneService.delete(id).then(resolve => {
          this.project.milestones_attributes.splice(i,1)
      })
    }
    else{
      this.project.milestones_attributes.splice(i,1)
    }
  }

  add(): void {
    var milestone = new Milestone()
   this.project.milestones_attributes.push(milestone)
  }


  updateProject(): void {
    this.projectShowed = true
    var routeSnapshot = this.route.snapshot
    this.id = routeSnapshot.params['project_id']
    this.projectService.get(this.id).then(project => {
      this.project = project
       console.log(this.project.milestones_attributes)
      if(this.project.milestones_attributes){
       var milestone = new Milestone()
       this.project.milestones_attributes.push(milestone)
      }
    })
    this.typeService.getList().then(types => {
      this.types = types
      this.project.type_id = types[0].id
    })
    this.userService.getList().then(users => {
      this.users = users
     /* if (users[0])
        this.project.leader_id = users[0].id
      if (!this.project.demander_id) this.project.demander_id = ""*/
    })
  }

 task_submit(): void {
    this.taskShowed = false
    this.taskService.update(this.task).then(res => {
      if (res.error) {
        if (res.error == "TOKEN-ERROR")
          return alert("无法处理，需要登录")
        return alert("出现错误，" + (res.msg || res.error))
      }
    })
    var argv = { project_id: this.id}
    this.taskService.get_task(argv).then(tasks => this.settask(tasks))
  }

  submit(): void {
    this.projectShowed = false
    this.projectService.update(this.project).then(res => {
      if (res.error) {
        if (res.error == "TOKEN-ERROR")
          return alert("无法处理，需要登录")
        return alert("出现错误，" + (res.msg || res.error))
      }
      project => this.project = project
    })
    var argv = { project_id: this.id}
    this.taskService.get_task(argv).then(tasks => this.settask(tasks))
  }

  settask(tasks: Array<Task>): void {
     var tp = moment()
     var standard = tp.subtract(15, 'days')
     this.top_date = standard.format("MM-DD");
     this.bottom_date = tp.add(30, 'days').format("MM-DD");
      this.tasks = tasks.filter(task => {
        task.s_date = moment( task.s_date).format("MM-DD")
        task.e_date = moment( task.e_date).format("MM-DD")
        task.s_width = this.compute(task.s_date, this.top_date) 
        task.e_width = this.compute(task.e_date, this.top_date)
        var w = task.e_width - task.s_width 
        if (w > 100) {
            task.s_e_width =  100
        }else {
           task.s_e_width = task.e_width - task.s_width  
        }

        task.milestones.filter(milestone => {
            milestone.date = moment( milestone.date).format("MM-DD")
            milestone.l_width = this.compute(milestone.date, this.top_date)
            return milestone
        })
        return task
      })
  }


  compute(s_date, t_date): number {
    var w 
    var s = moment(s_date)
    var e = moment(t_date)
    var count = s.diff(e, 'days')
    if(count > 0){
      w = (count /30)*100 
    }
    else {
      w = 0 
    }
    return  Math.round(w)
  }
}
